<?php
class MemberController extends Zend_Controller_Action
{
	public function init()
	{
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ()) {
			$this->view->identity = $auth->getIdentity ();
		}

	}

	public function homeAction()
	{
		$adminForm = new Form_Admin();
		$adminForm->setAction ( $this->_helper->url ( 'home', 'admin' ) );
		$adminForm->getElement ( 'username' )->setRequired ( FALSE );
		$adminForm->getElement ( 'password' )->setRequired ( FALSE );
		$adminForm->getElement ( 'password_confirm' )->setRequired ( FALSE );

		$mdlAdmins = new Model_Admin();

		if ($this->_request->isPost () && $adminForm->isValid ( $_POST )) {
			$data = $adminForm->getValues ();

			$currentAdmin = $mdlAdmins->getCurrentAdminInfor();
			if ($data ['username']) {
				$currentAdmin->username = $data ['username'];
				$currentAdmin->save ();
			}

			if ($data ['password']) {
				$currentAdmin->password = md5 ( $data ['password'] );
				$currentAdmin->save ();
			}
		} else {
			$currentAdmin = $mdlAdmins->getCurrentAdminInfor ()->toArray ();
			$adminForm->populate ( $currentAdmin );
		}

		$this->view->form = $adminForm;
	}

	public function blackMarketAction()
	{
		$auth = Zend_Auth::getInstance ();
		$storage = $auth->getIdentity();

		// fetch the news paginator adapter
		$mdlTips = new Model_Tips();
		$tips = $mdlTips->getList(" `result` IS NULL ", "date ASC", 1, 1)->toArray();
		$this->view->tip = $tips[0];

		if ($storage->role == 'member') {
			// valid payment
			$userID = $storage->id;

			$mdlPayment = new Model_Payments();
			$payments = $mdlPayment->getList("user_id = " . $userID , "created_ts DESC", 1, 1 )->toArray ();
			
			// never buy before
			if(count($payments) == 0) {
				return $this->_redirect ( 'member/payment' );
			}
				
			$payments = $payments[0];
			$tipID = $payments['tip_id'];
					
			if($tipID != $tips[0]["id"]) {
				return $this->_redirect ( 'member/payment' );
			}
		}

	}

	public function paymentAction() {

	}

	
	public function  verifyAction() {
		// read the post from PayPal system and add 'cmd'
		$req = 'cmd=_notify-synch';

		$tx_token = $_GET['tx'];
		$auth_token = "gTa6eJsGdu9JqFKwkGcWAFhVPgXhNrjxSBV550fq1lESqfdMhy3gvADK9Yy";
		$req .= "&tx=$tx_token&at=$auth_token";

		// post back to PayPal system to validate
		$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
		$fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30);
		// If possible, securely post back to paypal using HTTPS
		// Your PHP server will need to be SSL enabled
		// $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

		if (!$fp) {
			// HTTP ERROR
		} else {
			fputs ($fp, $header . $req);
			// read the body data 
			$res = '';
			$headerdone = false;
			while (!feof($fp)) {
				$line = fgets ($fp, 1024);
				if (strcmp($line, "\r\n") == 0) {
					// read the header
					$headerdone = true;
				} else if ($headerdone) {
					// header has been read. now read the contents
					$res .= $line;
				}
			}

			// parse the data
			$lines = explode("\n", $res);
			$keyarray = array();
			if (strcmp ($lines[0], "SUCCESS") == 0) {
			for ($i=1; $i<count($lines);$i++){
				list($key,$val) = explode("=", $lines[$i]);
				//echo "<p>urldecode($key)</p>";
				$keyarray[urldecode($key)] = urldecode($val);
			}
			// check the payment_status is Completed
			// check that txn_id has not been previously processed
			// check that receiver_email is your Primary PayPal email
			// check that payment_amount/payment_currency are correct
			// process payment
			$firstname = $keyarray['first_name'];
			$lastname = $keyarray['last_name'];
			$itemname = $keyarray['item_name'];
			$amount = $keyarray['payment_gross'];
			$mc_gross = $keyarray['mc_gross'];
			$payment_date = $keyarray['payment_date'];
			$payment_status = $keyarray['payment_status'];
			$payer_email = $keyarray['payer_email'];
			$txn_id = $keyarray['txn_id'];
			$mc_currency = $keyarray['mc_currency'];
			
			echo ("<p><h3>Thank you for your purchase!</h3></p>");

			echo ("<b>Payment Details</b><br>\n");
			echo ("<li>Name: $firstname $lastname</li>\n");
			echo ("<li>Item: $itemname</li>\n");
			echo ("<li>Amount: $amount</li>\n");
			echo ("<li>Currency: $mc_currency</li>\n");
			echo ("<li>mc_gross: $mc_gross</li>\n");
			echo ("<li>payment_date: $payment_date</li>\n");
			echo ("<li>payment_status: $payment_status</li>\n");
			echo ("<li>payer_email: $payer_email</li>\n");
			echo ("<li>Transaction ID: $txn_id</li>\n");
			
			echo ("");
			}
			else if (strcmp ($lines[0], "FAIL") == 0) {
			// log for manual investigation
			}

		}
		
		// close socket
		fclose ($fp);
		$this->_helper->viewRenderer->setNoRender();
	}
}